package org.nf.mvc.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author : LLH
 * @create 2021/5/26
 * 数据类型转换工具
 */

public class ConvertUtil {
    public static Object convert(String requestParameter,Class<?> parameterType) throws ParseException {
        Object value = null;

        if(parameterType.equals(String.class)){
            value = requestParameter;
        }else if(parameterType.equals(Integer.class) || parameterType.equals(Integer.TYPE)){
            value = Integer.valueOf(requestParameter);
        }else if(parameterType.equals(Short.class) || parameterType.equals(Short.TYPE)){
            value = Short.valueOf(requestParameter);
        }else if(parameterType.equals(Long.class) || parameterType.equals(Long.TYPE)){
            value = Long.valueOf(requestParameter);
        }else if(parameterType.equals(Float.class) || parameterType.equals(Float.TYPE)){
            value = Float.valueOf(requestParameter);
        }else if(parameterType.equals(Double.class) || parameterType.equals(Double.TYPE)){
            value = Double.valueOf(requestParameter);
        }else if(parameterType.equals(Byte.class) || parameterType.equals(Byte.TYPE)){
            value = Byte.valueOf(requestParameter);
        }else if(parameterType.equals(Boolean.class) || parameterType.equals(Boolean.TYPE)){
            value = Boolean.valueOf(requestParameter);
        }else if(parameterType.equals(Character.class) || parameterType.equals(Character.TYPE)){
            value = Character.valueOf(requestParameter.charAt(0));
        }else if(parameterType.equals(Date.class)){
            value = parseDate(requestParameter);
        }

        return value;
    }

    private static Date parseDate(String requestParameter) throws ParseException {
        Date date = null;

        if(!requestParameter.contains("-") && requestParameter.contains(":")){
            date=new SimpleDateFormat("HH:mm:ss").parse(requestParameter);
        }else if(requestParameter.contains("-") && !requestParameter.contains(":")){
            date=new SimpleDateFormat("yyyy-MM-dd").parse(requestParameter);
        }else{
            date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(requestParameter);
        }

        return date;
    }
}
